{% extends "base.html" %}

{% block title %}公共模板{% endblock %}

{% block head %}
{{ super() }}
<link href="{{ static_url('css/my.css') }}" rel="stylesheet" type="text/css">
{% endblock %}

{% block body %}
{{ utils.header(current_user, title="公共模板", sup=False) }}

<section class="tpl">
  <div id="error-msg"> {% if msg or msg != '' %}
    <pre>{{msg}}</pre>{% endif %}
  </div>
  <div class="container">
    <h2>
      已注册仓库
      {% if adminflg %}
      <button type="button" data-load-method="GET" class="btn btn-default modal_load"
        href="/subscribe/signup_repos/{{userid}}/" title="注册模板仓库">注册</button>
      <button type="button" data-load-method="GET" class="btn btn-default modal_load"
        href="/subscribe/unsubscribe_repos/{{userid}}/" title="取消注册此仓库">退订</button>
      {% endif %}
    </h2>
    <table id="register_repo" class="table table-hover tablesorter">
      <thead>
        <tr>
          {% if adminflg %}
          <th style="text-align:center" title="操作">操作</th>
          <th style="text-align:center" title="仓库序号">序号</th>
          {% endif %}
          <th style="text-align:center" title="注册的仓库名">仓库名</th>
          <th style="text-align:center" title="注册的仓库连接">链接</th>
          <th style="text-align:center" title="注册的仓库分支">分支</th>
          <th style="text-align:center" title="是否对仓库使用加速，仅对github有效">加速</th>
        </tr>
      </thead>
      <tbody>
        {% for repo in repos %}
        <tr>
          {% if adminflg %}
          <td style="text-align:center">
            <input type="checkbox" name="{{loop.index0}}" class="Repo checkbox"
              style="display: inline; min-height: unset;" onclick="repoNode.toggle(this)">
          </td>
          <td style="text-align:center">
            {{loop.index0}}
          </td>
          {% endif %}
          <td style="text-align:center">{{ repo.reponame }}</td>
          <td style="text-align:center">
            <a href="{{ repo.repourl }}" target="_blank" rel="noopener noreferrer">{{ repo.repourl }}</a>
          </td>
          <td style="text-align:center">{{ repo.repobranch }}</td>
          <td style="text-align:center">
            {% if adminflg %}
            <div class="btn-group btn-group-xs" role="group">
              <button type="button" class="btn btn-{{ 'success' if repo.repoacc else 'default' }} modal_load"
                data-load-method="POST" id="repo-acc-btn-{{ loop.index0 }}" data-repo-id="{{ loop.index0 }}"
                data-repo-acc="{{ 'true' if repo.repoacc else 'false' }}"
                href="/subscribe/toggle_acc/{{userid}}/?repo_id={{ loop.index0 }}&repo_acc={{ 'false' if repo.repoacc else 'true' }}"
                title="点击{{ '关闭' if repo.repoacc else '开启' }}加速">
                {{ '开启' if repo.repoacc else '关闭' }}
              </button>
            </div>
            {% else %}
            {{ '开启' if repo.repoacc else '关闭' }}
            {% endif %}
          </td>
        </tr>
        {% endfor %}
      </tbody>
    </table>
    <h2>
      模板
      {% if adminflg %}
      <a data-method="POST" class="btn btn-default" href="/subscribe/refresh/{{userid}}/?op=refresh"
        title="只更新,不清除缓存">强制更新</a>
      <a data-method="POST" class="btn btn-default" href="/subscribe/refresh/{{userid}}/?op=clear"
        title="有任务重复的时候，请尝试重建缓存">重建缓存</a>
      {% endif %}
      <button type="button" class="btn btn-default"
        onclick="window.open('https://github.com/qd-today/templates/discussions/171')" title="求模板链接"
        style="outline: none;">求模板</button>
    </h2>
    <div class="input-group margin-bottom-sm">
      <span class="input-group-addon"><i class="fa fa-search" aria-hidden="true"></i></span>
      <input id="search-input" class="search form-control input-lg" placeholder="搜索" autocomplete="off"
        spellcheck="false" autocorrect="off" tabindex="1" data-column="all">
      <span class="input-group-addon btn btn-default"><span type="span" class="fa fa-times-circle reset"
          aria-hidden="true"> 清空</span></span>
    </div>
    <table id="pubtpl_list" class="table table-hover tablesorter">
      <thead>
        <tr>
          <th style="text-align:center" title="模板操作区">操作</th>
          <th style="text-align:center" title="所属仓库">仓库</th>
          <th style="text-align:center" title="目标网站">网站</th>
          <th style="text-align:center" title="模板作者">作者</th>
          <th style="text-align:center" title="修改日期">修改日期</th>
          <th style="text-align:center" title="备注和修改日志">备注/日志</th>
        </tr>
      </thead>
      <tbody>
        {% for tpl in tpls | sort(attribute='date', reverse=True)%}
        <tr>
          <td style="text-align:center">
            <div class="btn-group btn-group-xs" role="group" aria-label="...">
              <button type="button" class="btn btn-default"
                onclick="window.open('/har/edit?reponame={{ tpl.reponame | urlencode }}&name={{ tpl.filename | urlencode }}')"
                id="{{ tpl.name }}" title="订阅此模板" style="outline: none;">订阅</button>
            </div>
            {% if tpl.commenturl != '' %}
            <div class="btn-group btn-group-xs" role="group" aria-label="...">
              <button type="button" class="btn btn-default" onclick="window.open('{{tpl.commenturl}}')"
                id="{{ tpl.name }}" title="跳转到评论区" style="outline: none;" rel="noopener noreferrer">评论</button>
            </div>
            {% endif %}
          </td>
          <td style="text-align:center">{{ tpl.reponame }}</td>
          <td style="text-align:center">{{ tpl.name }}</td>
          <td style="text-align:center">{{ tpl.author | safe }}</td>
          <td style="text-align:center">{{ tpl.date | safe }}</td>
          <td style="text-align:center">{{ tpl.comments | safe }}</td>
        </tr>
        {% endfor %}
      </tbody>
    </table>
  </div>
</section>

{% if adminflg %}
<script>
  $(function () {
    $('[data-toggle=popover]').popover({
      trigger: 'hover'
    });

    // 监听模态框关闭事件
    $('#modal_load').on('hide.bs.modal', function (e) {
      // 检查模态框内容，判断是否是加速状态切换的成功消息
      const modalContent = $('#modal_load .modal-content').text();
      if (modalContent.includes('加速状态已成功') || modalContent.includes('已成功开启') || modalContent.includes('已成功关闭')) {
        // 从模态框内容中提取仓库ID和新状态
        let repoId, newState;
        const matches = modalContent.match(/仓库\s*([^\s]+)\s*的加速/);

        // 查找被操作的按钮
        $('[id^=repo-acc-btn-]').each(function () {
          const $btn = $(this);
          const btnRepoId = $btn.attr('data-repo-id');
          const repoName = $('tr').find(`td:contains("${matches[1]}")`).first().text().trim();

          // 如果找到匹配的仓库按钮
          if ($btn.closest('tr').find('td:nth-child(3)').text().trim() === matches[1]) {
            // 获取当前状态
            const currentAcc = $btn.attr('data-repo-acc') === 'true';
            // 更新按钮状态
            const newAcc = !currentAcc;
            $btn.attr('data-repo-acc', newAcc ? 'true' : 'false');
            $btn.removeClass(newAcc ? 'btn-default' : 'btn-success');
            $btn.addClass(newAcc ? 'btn-success' : 'btn-default');
            $btn.text(newAcc ? '开启' : '关闭');
            $btn.attr('title', newAcc ? '点击关闭加速' : '点击开启加速');
            $btn.attr('href', `/subscribe/toggle_acc/{{userid}}/?repo_id=${encodeURIComponent(btnRepoId)}&repo_acc=${currentAcc ? 'true' : 'false'}`);
          }
        });
      }
    });
  });
</script>
<script>
  const repoNode = {
    selectedRepoNodesJSON: '{}',

    get selectedRepoNodes() {
      return this.getSelectedRepoNodes()
    },

    set selectedRepoNodes(val) {
      this.setSelectedRepoNodes(val)
    },

    getSelectedRepoNodes: function () {
      if (this.selectedRepoNodesJSON == '{}') {
        if (typeof (sessionStorage.selectedrepo) != "undefined") {
          this.selectedRepoNodesJSON = sessionStorage.selectedrepo
        }
      }
      return JSON.parse(this.selectedRepoNodesJSON)
    },

    setSelectedRepoNodes: function (val) {
      this.selectedRepoNodesJSON = JSON.stringify(val)
      sessionStorage.selectedrepo = JSON.stringify(val)
    },

    toggle: function (repoNode, uncheck) {
      let _selectedRepoNodes = this.selectedRepoNodes
      _selectedRepoNodes[repoNode.name] = repoNode.checked
      this.selectedRepoNodes = _selectedRepoNodes
      if (!uncheck) {
        (typeof setRepoGroupChecked == 'function') && setRepoGroupChecked(repoNode.className)
      }
    },


    init: function () {
      let _selectedRepoNodes = this.selectedRepoNodes
      let _classNames = {}
      for (let key in _selectedRepoNodes) {
        let reponodes = document.getElementsByName(key);
        if (reponodes.length > 0) {
          reponodes[0].checked = _selectedRepoNodes[key]
          // 将已选中的reponode的className 存储在_classNames中
          if (_selectedRepoNodes[key]) {
            _classNames[reponodes[0].className] = true
          }
        }
      }

      for (let key in _classNames) {
        (typeof setRepoGroupChecked == 'function') && setRepoGroupChecked(key)
      }
    }

  }

  /**
   *  修改全选按钮样式
   *  在repoNode.init()之前加载
   *
   **/
  function setRepoGroupChecked(className) {
    let _eles = document.getElementsByName(className)
    let _nodeGroupChecked
    for (let i = 0; i < _eles.length; i++) {
      if (_eles[i].nodeName.toLowerCase() == 'input' &&
        _eles[i].getAttribute('type') == 'checkbox'
      ) {
        _nodeGroupChecked = _eles[i]
      }
    }
    if (typeof _nodeGroupChecked == 'undefined') return;
    let _checkedNum = 0
    const _repoNodes = document.getElementsByClassName(className)

    for (key in _repoNodes) {
      if (_repoNodes[key].checked == true) {
        _checkedNum++
      }
    }

    if (_checkedNum == _repoNodes.length) {
      _nodeGroupChecked.indeterminate = false;
      _nodeGroupChecked.checked = true;
    } else if (_checkedNum > 0) {
      _nodeGroupChecked.indeterminate = true;
      _nodeGroupChecked.checked = false;
    } else {
      _nodeGroupChecked.indeterminate = false;
      _nodeGroupChecked.checked = false;
    }
  }

  // 页面加载后初始化
  repoNode.init()

</script>
{% endif %}
<script>
  $(function () {
    // Extend the themes to change any of the default class names
    $.tablesorter.themes.bootstrap = {
      // these classes are added to the table. To see other table classes available,
      // look here: http://getbootstrap.com/css/#tables
      table: 'table table-hover',
      caption: 'caption',
      // header class names
      header: 'bootstrap-header', // give the header a gradient background (theme.bootstrap_2.css)
      sortNone: '',
      sortAsc: '',
      sortDesc: '',
      active: '', // applied when column is sorted
      hover: '', // custom css required - a defined bootstrap style may not override other classes
      // icon class names
      icons: '', // add "bootstrap-icon-white" to make them white; this icon class is added to the <i> in the header
      iconSortNone: 'bootstrap-icon-unsorted', // class name added to icon when column is not sorted
      iconSortAsc: 'glyphicon glyphicon-chevron-up', // class name added to icon when column has ascending sort
      iconSortDesc: 'glyphicon glyphicon-chevron-down', // class name added to icon when column has descending sort
      filterRow: '', // filter row class; use widgetOptions.filter_cssFilter for the input/select element
      footerRow: '',
      footerCells: '',
      even: '', // even row zebra striping
      odd: ''  // odd row zebra striping
    };
    $("#register_repo").tablesorter({
      theme: "bootstrap",
      sortList: [[1, 0]],
      headers: { 0: { sorter: false, parser: false } },
      headerTemplate: '{content} {icon}', // needed to add icon for jui theme
      widgets: ['uitheme']
    });
    $("#pubtpl_list").tablesorter({
      theme: "bootstrap",
      sortList: [[4, 1], [2, 0]],
      headers: { 0: { sorter: false, parser: false } },
      headerTemplate: '{content} {icon}', // needed to add icon for jui theme
      widgets: ['uitheme', 'filter'],
      widgetOptions: {
        // using the default zebra striping class name, so it actually isn't included in the theme variable above
        // this is ONLY needed for bootstrap theming if you are using the filter widget, because rows are hidden
        // zebra : ["even", "odd"],
        // class names added to columns when sorted
        // reset filters button
        filter_reset: ".reset",
        filter_external: '.search',
        filter_columnFilters: false,
        // extra css class name (string or array) added to the filter element (input or select)
        filter_cssFilter: "form-control"
        // set the uitheme widget to use the bootstrap theme class names
        // this is no longer required, if theme is set
        // ,uitheme : "bootstrap"
      }
    });
  })
</script>


{{ utils.modal_load() }}
{{ utils.apost() }}
{% endblock %}
